package com.monicash.monicash.base

import androidx.lifecycle.ViewModel
import com.google.gson.GsonBuilder
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.ResponseBody
import retrofit2.Response
import java.nio.charset.StandardCharsets

open class BaseModle : ViewModel(){

    val replaceSymbols = "MiLuPage"


    fun getMiLuPageJson(valueMap: Map<String, String>?,addHeader:Boolean) :String{
        val params: MutableMap<String, Any?> = HashMap()
        try {
            params["body"] = valueMap
            if (!addHeader) {
                params["headers"] = getMiLuPageHead()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        var requestValue = GsonBuilder()
            .setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER)
            .create()
            .toJson(params)
        if (addHeader) {
            requestValue = GsonBuilder()
                .setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER)
                .create()
                .toJson(valueMap)
        }
        var fParams = RSAUtil.encryptDataByPublicKey(
            requestValue.toString().toByteArray(StandardCharsets.UTF_8),
            RSAUtil.keyStrToMiLuPagePublicKey(RSAUtil.publicKeyString)
        )
        if (addHeader) {
            fParams = requestValue
        }
        return fParams
    }

    fun Any.toJsonRequestBody(format: String = "application/json"): RequestBody {
        return GsonBuilder()
            .setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER)
            .create()
            .toJson(this).toRequestBody(format.toMediaType())
    }

    fun Any.toStringRequestBody(format: String = "application/json"): RequestBody {
        return format.toRequestBody(format.toMediaType())
    }

    private fun getMiLuPageHead(): Map<String,Any> {
        val app_id = BaseApplication.getInstance().packageName
        val headMap = HashMap<String,Any>()
        headMap["App_id"] = "com.mc.moring"
        headMap["App_name"] = "MONICASH"
        headMap["App_version"] = "1.0.0"
        headMap["accept_language"] = "es"
        headMap["Authorization"] = ""
        return headMap
    }

    fun decryptingMiLuPageData(response:Response<ResponseBody>):String{
        val value = response.body()?.string()
        val valueResult = RSAUtil.getDecryptApiMiLuPageData(value?:"")
        return valueResult?:""
    }
}